package com.flame.user.service;

import java.util.ArrayList;
import java.util.List;

import com.flame.auth.core.constants.AuthConstants;
import com.flame.user.controller.vo.RoleVo;
import com.flame.user.entity.Role;
import com.flame.user.exception.UserExceptionMessage;
import com.flame.user.exception.UserRuntimeException;
import com.flame.user.mapper.ObjAuthMapper;
import com.flame.user.mapper.RoleMapper;
import com.flame.user.controller.vo.SimpleRoleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * flame_role 角色信息表
 *
 * @author 吴欣童
 * @since 2022-12-15 10:04:46
 */
@Service
public class RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private ObjAuthMapper objAuthMapper;

    public List<Role> pageRole(RoleVo roleVo) {
        return roleMapper.page(roleVo);
    }

    public void addRole(Role role) {
        Role dbRole = roleMapper.selectById(role.getRoleCode());
        if (dbRole != null) {
            throw new UserRuntimeException(UserExceptionMessage.ROLE_EXIST);
        }
        roleMapper.insert(role);
    }

    public void updateRole(Role role) {
        roleMapper.updateById(role);
    }

    public void deleteRole(Role role) {
        // 1、删除角色关联的权限信息
        objAuthMapper.deleteByObjIdAndObjType(role.getRoleCode(), AuthConstants.OBJ_TYPE_ROLE);
        // 2、删除角色
        roleMapper.deleteById(role.getRoleCode());
    }

    public List<SimpleRoleVo> getRoleSimpleById(List<String> roleCodeList) {
        List<SimpleRoleVo> res = new ArrayList<>();
        for (String roleCode : roleCodeList) {
            Role role = roleMapper.selectById(roleCode);
            SimpleRoleVo simpleRoleVo = new SimpleRoleVo();
            BeanUtils.copyProperties(role, simpleRoleVo);
            res.add(simpleRoleVo);
        }
        return res;
    }
}
